extends Area2D
class_name EnemyHitBoxComponent

@export var density: int = 10
@export var length: float = 20
@export var range_angle: float = 200
@export var speed: int = 10
@export var hit_body_record: Array[PlayerHurtBoxComponent] = []
# 攻击前摇时间
@export var before_attack_time: float = 0.01
@export var damage = 20
func _init() -> void:
	area_entered.connect(_on_area_entered)

func _on_area_entered(hurtbox: PlayerHurtBoxComponent) -> void:
	if not hit_body_record.has(hurtbox):
		hit_body_record.append(hurtbox)
	else:
		return
	print("[Hit] %s => %s" % [self.owner.name, hurtbox.owner.name])
	# 使对方受伤
	hurtbox.hurt(self, damage)

func _clear_record():
	hit_body_record.clear()

# 近战攻击, 使用求生之路的横扫扫描
func melee_attack(attack_speed : int) -> void:
	await get_tree().create_timer(before_attack_time).timeout

	var to_player = Utils.player.global_position - global_position

	# 判断是左右半圆还是上下半圆
	var horizontal : bool = abs(to_player.x) >= abs(to_player.y)

	# 选一个“基准向量”，后面所有 segment 都在它左右(or 上下) ±range_angle/2 范围内旋转
	var basis : Vector2
	if horizontal:
		# 基准向量指向左右
		basis = Vector2(sign(to_player.x), 0) * length        # (±length, 0)
	else:
		# 基准向量指向上下
		basis = Vector2(0, sign(to_player.y)) * length        # (0, ±length)

	# 每一个碰撞 segment
	for i in density:
		var shape := SegmentShape2D.new()
		var t   : float = float(i) / float(density - 1)       # 0 … 1
		var offset_angle = lerp(-deg_to_rad(range_angle)/2,
								+deg_to_rad(range_angle)/2, t)
		shape.a = Vector2.ZERO
		shape.b = basis.rotated(offset_angle)                 # 旋转以后得到真正的方向

		var cs := CollisionShape2D.new()
		cs.shape = shape
		cs.debug_color = Color("#ffff00c8")
		call_deferred("add_child", cs)

		# 延时让下一个 segment 出来
		await get_tree().create_timer(
			0.2 * (1.0 / speed) * (1.0 / density) *
			(17.0 / density) / attack_speed).timeout

	# 段扫完以后把碰撞体删掉
	await get_tree().create_timer(0.1).timeout
	for child in get_children():
		child.set_deferred("disabled", true)
		if child.is_inside_tree():
			remove_child(child)
		await get_tree().create_timer(0.01).timeout

	hit_body_record.clear()
